package net.lahuobao.mall.controller.admin;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lahuobao.mall.entity.admin.MallArticleEntity;
import net.lahuobao.mall.service.admin.MallArticleServiceI;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.DataGridReturn;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.web.system.pojo.base.TSFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import net.lahuobao.mall.entity.admin.MallArticleCategoryEntity;
import net.lahuobao.mall.service.admin.MallArticleCategoryServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;

import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 文章分类
 * @author zhangdaihao
 * @date 2016-08-25 11:01:09
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/mallArticleCategoryController")
public class MallArticleCategoryController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MallArticleCategoryController.class);

	@Autowired
	private MallArticleCategoryServiceI mallArticleCategoryService;

	@Autowired
	private MallArticleServiceI mallArticleService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private Validator validator;
	


	/**
	 * 文章分类列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/mall/admin/mallArticleCategoryList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(MallArticleCategoryEntity mallArticleCategory,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(MallArticleCategoryEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallArticleCategory, request.getParameterMap());
		DataGridReturn re =  this.mallArticleCategoryService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除文章分类
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(MallArticleCategoryEntity mallArticleCategory, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		mallArticleCategory = systemService.getEntity(MallArticleCategoryEntity.class, mallArticleCategory.getId());
		//判断是否为父节点
		if(null == mallArticleCategory.getParentcategoryid()){//是
			//判断有无子节点--有 不删除
			CriteriaQuery cq = new CriteriaQuery(MallArticleCategoryEntity.class);
			cq.eq("parentcategoryid", mallArticleCategory.getId());
			cq.add();
			List<MallArticleCategoryEntity> list = mallArticleCategoryService.getListByCriteriaQuery(cq, false);
			if(list.size() > 0){//有
				j.setSuccess(false);
				j.setMsg("删除失败！该分类为父节点，并且该分类下存在子分类，请先删除子分类!");
				return  j;
			}else{//无
				return  del(mallArticleCategory);
			}
		}else{//否
			return del(mallArticleCategory);
		}

	}


	/**
	 * 添加文章分类
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(MallArticleCategoryEntity mallArticleCategory, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(mallArticleCategory.getId())) {
			message = "文章分类更新成功";
			MallArticleCategoryEntity t = mallArticleCategoryService.get(MallArticleCategoryEntity.class, mallArticleCategory.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(mallArticleCategory, t);
				mallArticleCategoryService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "文章分类更新失败";
			}
		} else {
			message = "文章分类添加成功";
			if(StringUtil.isEmpty(mallArticleCategory.getParentcategoryid())){
				mallArticleCategory.setParentcategoryid(null);
			}
			mallArticleCategoryService.save(mallArticleCategory);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 文章分类列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(MallArticleCategoryEntity mallArticleCategory, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(mallArticleCategory.getId())) {
			mallArticleCategory = mallArticleCategoryService.getEntity(MallArticleCategoryEntity.class, mallArticleCategory.getId());
			req.setAttribute("mallArticleCategoryPage", mallArticleCategory);
		}
		return new ModelAndView("net/lahuobao/mall/admin/mallArticleCategory");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<MallArticleCategoryEntity> list() {
		List<MallArticleCategoryEntity> listMallArticleCategorys=mallArticleCategoryService.getList(MallArticleCategoryEntity.class);
		return listMallArticleCategorys;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		MallArticleCategoryEntity task = mallArticleCategoryService.get(MallArticleCategoryEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody MallArticleCategoryEntity mallArticleCategory, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallArticleCategoryEntity>> failures = validator.validate(mallArticleCategory);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallArticleCategoryService.save(mallArticleCategory);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = mallArticleCategory.getId();
		URI uri = uriBuilder.path("/rest/mallArticleCategoryController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody MallArticleCategoryEntity mallArticleCategory) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallArticleCategoryEntity>> failures = validator.validate(mallArticleCategory);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallArticleCategoryService.saveOrUpdate(mallArticleCategory);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		mallArticleCategoryService.deleteEntityById(MallArticleCategoryEntity.class, id);
	}


	/**
	 * 父级权限下拉菜单
	 */
	@RequestMapping(params = "categorytree")
	@ResponseBody
	public List<ComboTree> categorytree(HttpServletRequest request, ComboTree comboTree) {
		CriteriaQuery cq = new CriteriaQuery(MallArticleCategoryEntity.class);
		if (null != request.getParameter("selfId")) {
			cq.notEq("id", request.getParameter("selfId"));
		}
		if (comboTree.getId() != null) {
			cq.eq("parentcategoryid", comboTree.getId());
		}
		if (comboTree.getId() == null) {
			cq.isNull("parentcategoryid");
		}
		cq.add();
		//设置选择树
		List<MallArticleCategoryEntity> categoryList = mallArticleCategoryService.getListByCriteriaQuery(cq, false);
		List<MallArticleCategoryEntity> categoryListFor = new ArrayList<MallArticleCategoryEntity>();
		List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		ComboTreeModel comboTreeModel = new ComboTreeModel("id", "categoryName", "categorys");
		categoryListFor.addAll(categoryList);
		comboTrees = systemService.ComboTree(categoryList, comboTreeModel, null, false);
		MutiLangUtil.setMutiTree(comboTrees);
		//设置Attributes
		for(ComboTree com : comboTrees){
			for(MallArticleCategoryEntity cate : categoryListFor){
				if(cate.getId().equals(com.getId())){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("ismulty", cate.getIsmulty());
					com.setAttributes(map);
				}
			}
		}
		return comboTrees;
	}


	/**
	 * 判断是否有文章引用
	 * @param articlecategoryid
	 * @return
	 */
	private boolean isArticleUser(String articlecategoryid){
		CriteriaQuery cq = new CriteriaQuery(MallArticleEntity.class);
		cq.eq("articlecategoryid", articlecategoryid);
		cq.add();
		List<MallArticleEntity> list = mallArticleService.getListByCriteriaQuery(cq, false);
		return list.size() > 0 ? true : false;
	}

	/**
	 * 删除文章分类
	 * @return
	 */
	private AjaxJson del(MallArticleCategoryEntity mallArticleCategory){
		AjaxJson json = new AjaxJson();
		String message = "";
		// 判断有无文章引用
		if(this.isArticleUser(mallArticleCategory.getId())){//有
			json.setSuccess(false);
			message = "删除失败！该分类正在被文章引用，不能删除，如需删除，请先删除该分类下面的文章！";
		}else{
			message = "删除文章分类成功";
			mallArticleCategoryService.delete(mallArticleCategory);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}
		json.setMsg(message);
		return json;
	}

}
